{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "# setting the environment variables\n",
    "import sys\n",
    "import os\n",
    "\n",
    "sys.path.insert(0, os.path.abspath('..'))\n",
    "\n",
    "from config import set_environment\n",
    "set_environment()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-10T16:08:57.038503Z",
     "start_time": "2024-04-10T16:08:57.033395Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## ConversationBufferMemory"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello! I'm doing well, thank you for asking. I've been busy processing a lot of information and learning new things. How can I assist you today?\n",
      "The weather today is partly cloudy with a high of 75 degrees Fahrenheit and a 20% chance of rain in the afternoon. The wind is coming from the northwest at 10 mph. Is there anything else you would like to know?\n",
      "[HumanMessage(content='Hi, how are you?'), AIMessage(content=\"Hello! I'm doing well, thank you for asking. I've been busy processing a lot of information and learning new things. How can I assist you today?\"), HumanMessage(content=\"What's the weather like today?\"), AIMessage(content='The weather today is partly cloudy with a high of 75 degrees Fahrenheit and a 20% chance of rain in the afternoon. The wind is coming from the northwest at 10 mph. Is there anything else you would like to know?')]\n"
     ]
    }
   ],
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "from langchain.chains.conversation.base import ConversationChain\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "llm = ChatOpenAI(\n",
    "  model_name=\"gpt-3.5-turbo\", temperature=0, streaming=True\n",
    ")\n",
    "\n",
    "# Creating a conversation chain with memory\n",
    "memory = ConversationBufferMemory()\n",
    "chain = ConversationChain(llm=llm, memory=memory)\n",
    "# User inputs a message\n",
    "user_input = \"Hi, how are you?\"\n",
    "# Processing the user input in the conversation chain\n",
    "response = chain.predict(input=user_input)\n",
    "# Printing the response\n",
    "print(response)\n",
    "# User inputs another message\n",
    "user_input = \"What's the weather like today?\"\n",
    "# Processing the user input in the conversation chain\n",
    "response = chain.predict(input=user_input)\n",
    "# Printing the response\n",
    "print(response)\n",
    "# Printing the conversation history stored in memory\n",
    "print(memory.chat_memory.messages)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-10T16:09:10.934779Z",
     "start_time": "2024-04-10T16:09:08.026186Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## ConversationBufferWindowMemory"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationBufferWindowMemory\n",
    "\n",
    "memory = ConversationBufferWindowMemory(k=1)\n",
    "memory.save_context({\"input\": \"hi\"}, {\"output\": \"whats up\"})\n",
    "memory.save_context({\"input\": \"not much you\"}, {\"output\": \"not much\"})\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-10T16:38:34.581653Z",
     "start_time": "2024-04-10T16:38:34.575975Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "data": {
      "text/plain": "{'history': 'Human: not much you\\nAI: not much'}"
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-10T16:38:42.399971Z",
     "start_time": "2024-04-10T16:38:42.395390Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Customizations"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/ben/anaconda3/envs/newgen/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new ConversationChain chain...\u001B[0m\n",
      "Prompt after formatting:\n",
      "\u001B[32;1m\u001B[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "\n",
      "Human: hello\n",
      "AI Assistant:\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": "{'input': 'hello',\n 'history': '',\n 'response': ' Hello! How can I assist you today?'}"
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_openai import OpenAI\n",
    "from langchain.chains import ConversationChain\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "llm = OpenAI(temperature=0)\n",
    "template = \"\"\"The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
    "\n",
    "Current conversation:\n",
    "{history}\n",
    "Human: {input}\n",
    "AI Assistant:\"\"\"\n",
    "PROMPT = PromptTemplate(input_variables=[\"history\", \"input\"], template=template)\n",
    "conversation = ConversationChain(\n",
    "    prompt=PROMPT,\n",
    "    llm=llm,\n",
    "    verbose=True,\n",
    "    memory=ConversationBufferMemory(ai_prefix=\"AI Assistant\"),\n",
    ")\n",
    "conversation(\"hello\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-10T16:43:46.754727Z",
     "start_time": "2024-04-10T16:43:45.874021Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new ConversationChain chain...\u001B[0m\n",
      "Prompt after formatting:\n",
      "\u001B[32;1m\u001B[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "Human: hello\n",
      "AI Assistant:  Hello! How can I assist you today?\n",
      "Human: What's your name?\n",
      "AI Assistant:\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": "{'input': \"What's your name?\",\n 'history': 'Human: hello\\nAI Assistant:  Hello! How can I assist you today?',\n 'response': ' My name is AI Assistant. I am an artificial intelligence designed to assist and communicate with humans. I do not have a physical form, but I exist in the digital world. Is there anything else you would like to know about me?'}"
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation(\"What's your name?\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-10T16:44:03.746313Z",
     "start_time": "2024-04-10T16:44:02.532800Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## ConversationSummaryMemory"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationSummaryMemory\n",
    "from langchain_openai import OpenAI\n",
    "\n",
    "# Initialize the summary memory and the language model\n",
    "memory = ConversationSummaryMemory(llm=OpenAI(temperature=0))\n",
    "# Save the context of an interaction\n",
    "memory.save_context({\"input\": \"hi\"}, {\"output\": \"whats up\"})\n",
    "# Load the summarized memory\n",
    "memory.load_memory_variables({})\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## CombinedMemory"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new ConversationChain chain...\u001B[0m\n",
      "Prompt after formatting:\n",
      "\u001B[32;1m\u001B[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "Summary of conversation:\n",
      "\n",
      "Current conversation:\n",
      "\n",
      "Human: Hi!\n",
      "AI:\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": "{'input': 'Hi!',\n 'chat_history_lines': '',\n 'history': '',\n 'response': \" Hello there! It's nice to meet you. My name is AI and I am an artificial intelligence designed to assist and communicate with humans. How can I help you today?\"}"
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import OpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.chains import ConversationChain\n",
    "from langchain.memory import (\n",
    "   ConversationBufferMemory, CombinedMemory, ConversationSummaryMemory\n",
    ")\n",
    "\n",
    "# Initialize language model (with desired temperature parameter)\n",
    "llm = OpenAI(temperature=0)\n",
    "# Define Conversation Buffer Memory (for retaining all past messages)\n",
    "conv_memory = ConversationBufferMemory(memory_key=\"chat_history_lines\", input_key=\"input\")\n",
    "# Define Conversation Summary Memory (for summarizing conversation)\n",
    "summary_memory = ConversationSummaryMemory(llm=llm, input_key=\"input\")\n",
    "# Combine both memory types\n",
    "memory = CombinedMemory(memories=[conv_memory, summary_memory])\n",
    "# Define Prompt Template\n",
    "_DEFAULT_TEMPLATE = \"\"\"The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
    "Summary of conversation:\n",
    "{history}\n",
    "Current conversation:\n",
    "{chat_history_lines}\n",
    "Human: {input}\n",
    "AI:\"\"\"\n",
    "PROMPT = PromptTemplate(input_variables=[\"history\", \"input\", \"chat_history_lines\"], template=_DEFAULT_TEMPLATE)\n",
    "# Initialize the Conversation Chain\n",
    "conversation = ConversationChain(llm=llm, verbose=True, memory=memory, prompt=PROMPT)\n",
    "# Start the conversation\n",
    "conversation(\"Hi!\")\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-10T16:58:32.926643Z",
     "start_time": "2024-04-10T16:58:31.111112Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
